import Prize from '../../../database/models/prize'

export const typeDefs = `
  type Prize{
    _id: String
    name: String
    imageUrl:String
    onStock:Boolean
    index: Int
    gem:Int
    chance: Float
  }
`

export const queryDefs = `
  getPrizes: [Prize]!
`

export const mutationDefs = `
  createPrize(
    name:String!,
    imageUrl:String!,
    gem: Int!,
    index: Int!,
    chance: Float!
  ):Prize!
  
  deletePrize(_id:String!) : Boolean!
  
  putOnStock(
    _id: String!
  ):Prize!
  
  putOffStock(
    _id: String!
  ):Prize!     
`

export const resolvers = {
  Query: {
    async getPrizes() {
      const records = await Prize.find()
        .sort({index: 1})
        .lean()
      return records
    }
  },

  Mutation: {
    async createPrize(_, {name, imageUrl, gem, index, chance}) {
      const prize = new Prize({
        name, imageUrl, gem, chance, index,
        onStock: false
      })
      try {
        await prize.save()
      } catch (e) {
        throw Error(`重复的序号 ${index}`)
      }
      return prize
    },

    async deletePrize(_, {_id}) {
      await Prize.remove({_id})
      return true
    },

    async putOnStock(_, {_id}) {
      const prize = await Prize.findOne({_id})
      if (!prize) {
        throw Error('没有此商品')
      }

      const allOnStockPrize = await Prize.find({state: "on"}).select({chance: 1}).lean()

      const currentTotalChance = allOnStockPrize.reduce((sumOfChance, p) => sumOfChance + p.chance, 0)

      if (currentTotalChance + prize.chance >= 1) {
        throw Error('概率设置错误 (所有中奖概率的和应该小于等于1)')
      }

      prize.onStock = true
      await prize.save()

      return prize.toObject()
    },

    async putOffStock(_, {_id}) {
      const prize = await Prize.findOne({_id})
      if (!prize) {
        throw Error('没有此商品')
      }
      prize.onStock = false
      await prize.save()

      return prize.toObject()
    }
  }
}
